package com.safe.app.config.oos;

import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.safe.app.config.oos.config.QiniuCloudConfig;
import com.safe.app.utils.exceptions.base.ErrorMsgException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;

/**
 * 云存储操作工具类
 *
 * @author h2l
 */
@Slf4j
public class CloudStorageServiceImpl extends CloudStorageService {


    private UploadManager uploadManager;

    private String token;


    public CloudStorageServiceImpl(QiniuCloudConfig config) {
        this.config = config;

        //初始化
        init();
    }

    private void init() {
        uploadManager = new UploadManager(new Configuration(Zone.autoZone()));
        token = Auth.create(config.getQiniuAccessKey(), config.getQiniuSecretKey()).
                uploadToken(config.getQiniuBucketName());
    }

    @Override
    public String upload(byte[] data, String path) throws Exception {
        try {
            Response res = uploadManager.put(data, path, token);
            if (!res.isOK()) {
                throw new RuntimeException("上传七牛出错：" + res.toString());
            }
        } catch (Exception e) {
            throw new ErrorMsgException("上传文件失败，请核对七牛配置信息");
        }

        return config.getQiniuDomain() + "/" + path;
    }

    @Override
    public String upload(InputStream inputStream, String path) throws Exception {
        try {
            byte[] data = IOUtils.toByteArray(inputStream);
            return this.upload(data, path);
        } catch (IOException e) {
            throw new ErrorMsgException("上传文件失败");
        }
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) throws Exception {
        return upload(data, getPath(config.getQiniuPrefix(), suffix));
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) throws Exception {
        return upload(inputStream, getPath(config.getQiniuPrefix(), suffix));
    }
}
